package threshold

/**
 *	author:zd.zhang
 */

/**
 *	<summary>判断直方图是否为双峰</summary>
 *	<param name="histGram">直方图数据</param>
 *	<returns></returns>
 */
func isDimodal(histGram []float32) bool {
	count := 0
	for i := 1; i < 255; i++ {
		if histGram[i] > histGram[i-1] && histGram[i] > histGram[i+1] {
			count++
			if count > 2 {
				return false
			}
		}
	}
	return count == 2
}

/**
 *	<summary>转化直方图为平滑双峰</summary>
 *	<param name="image">图片对象</param>
 *	<returns>双峰位置</returns>
 */
func dimodal(histGram []int) ([]float32, []int) {
	histGramC := make([]float32, 256)
	for i, g := range histGram {
		histGramC[i] = float32(g)
	}
	var tryCount int = 0
	for !isDimodal(histGramC) {
		for i := 1; i < 255; i++ {
			histGramC[i] = histGramC[i-1]*0.15 + histGramC[i]*0.7 + histGramC[i+1]*0.15
		}
		tryCount++
		if tryCount > 1000 {
			return nil, nil
		}
	}
	index := 0
	dimodal := make([]int, 2, 2)
	for i := 1; i < 255; i++ {
		if histGramC[i] > histGramC[i-1] && histGramC[i] > histGramC[i+1] {
			dimodal[index] = i
			index++
		}
	}
	return histGramC, dimodal
}

/**
 *	<summary>获取直方图中最小灰度值</summary>
 *	<param name="histGram">直方图数据</param>
 *	<returns></returns>
 */
func getMinHistGram(histGram []int) uint8 {
	for i, v := range histGram {
		if v > 0 {
			return uint8(i)
		}
	}
	return 0
}

/**
 *	<summary>获取直方图中最大灰度值</summary>
 *	<param name="histGram">直方图数据</param>
 *	<param name="min">最小灰度值</param>
 *	<returns></returns>
 */
func getMaxHistGram(histGram []int, min uint8) uint8 {
	for i := 255; i > int(min); i-- {
		if histGram[i] > 0 {
			return uint8(i)
		}
	}
	return min
}
